<route lang="yaml">
  meta:
    title: 工单派遣
</route>

<script setup>
import axios from 'axios'
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

// 表格数据
const tableData = ref([])
// 使用 ref 创建对 el-table 的引用
const tableRef = ref(null)

// 筛选条件
const selectedRegion = ref('')
const selectedCustomer = ref('')
// 分页相关
const currentPage = ref(1)
const currentWorkerPage = ref(1)
const pageSize = 10
const totalNum = ref(0)
const totalWorker = ref(0)

function handlePageChange(page) {
  currentPage.value = page
  fetchData({ pageNum: currentPage.value })
}
function handleWorkerPageChange(page) {
  currentWorkerPage.value = page
  fetchWorkerData({ pageNum: currentWorkerPage.value })
}
// 派遣对话框部分
const isDispatchDialogVisible = ref(false)
const currentOrderId = ref(null)
const responseTime = ref(null) // 新增响应时间变量

function dispatchOrder(id) {
  currentOrderId.value = id // 设置当前工单号
  isDispatchDialogVisible.value = true // 打开对话框
}

const searchQuery = ref('')
const selectedWorker = ref(null)
const workerPageSize = ref(5)
const loading = ref(false)

const electrician = ref([])
const selectedRows = ref([])

function handleSelectionChange(selection) {
  if (selection.length <= 1) {
    // 保持选中状态为最后一个选择的工人
    selectedWorker.value = selection[0]
    console.log('selectedWorker', selectedWorker.value)
  }
  else {
    tableRef.value.clearSelection()
    selectedWorker.value = selection[selection.length - 1]
    console.log('selectedWorker', selectedWorker.value)
  }
}
// 确认派遣
async function confirmDispatch() {
  console.log('派遣工单信息：', {
    workOrderCode: currentOrderId.value,
    electricianCode: selectedWorker.value.electricianCode,
    electricianName: selectedWorker.value.electricianName,
    electricianPhone: selectedWorker.value.electricianPhone,
    responseTime: responseTime.value,
  })
  try {
    const response = await axios.post('https://www.cqwuyang.cn/ElectricManageService/workOrder/dispatch', {
      workOrderCode: currentOrderId.value,
      electricianCode: selectedWorker.value.electricianCode,
      electricianName: selectedWorker.value.electricianName,
      electricianPhone: selectedWorker.value.electricianPhone,
      workOrderRequirementDate: responseTime.value,
    })
    if (response.data) {
      console.log('定向派遣结果:')
      console.log(response.data)
      isDispatchDialogVisible.value = false
      if (response.data.code === 200) {
        window.location.reload()
      }
    }
  }
  catch (error) {
    console.error('获取数据时出错:', error)
  }
}
// 发布对话框部分
const isReleaseDialogVisible = ref(false)
// 发布抢单
function releaseOrder(workOrderCode) {
  currentOrderId.value = workOrderCode // 设置当前工单号
  isReleaseDialogVisible.value = true // 打开对话框
}
// 确认发布
async function confirmRelease() {
  isReleaseDialogVisible.value = false
  const workOrderCode = currentOrderId.value
  const workOrderRequirementDate = responseTime.value
  try {
    const response = await axios.post('https://www.cqwuyang.cn/ElectricManageService/workOrder/publish', {
      workOrderCode,
      workOrderRequirementDate,
    })
    if (response.data) {
      console.log('发布抢单结果:')
      console.log(response.data)
      window.location.reload()
      if (response.data === 200) {
        window.location.reload()
      }
    }
  }
  catch (error) {
    console.error('获取数据时出错:', error)
  }
}
const router = useRouter()
function openOrderPage(row) {
  console.log(row.workOrderCode)
  const to = router.resolve({
    name: 'order-details',
    params: { id: row.workOrderCode },
  })
  const httpUrl = to.href.replace(/^https:\/\//, 'http://')
  window.open(httpUrl, '_blank')
  // window.open(to.href, '_blank')
}

function resetSelection() {
  selectedWorker.value = null
  responseTime.value = null
  if (tableRef.value) {
    tableRef.value.clearSelection()
  }
}
// 页面读取数据
async function fetchData({ pageNum = '1', feedbackType = 3, workOrderState = 0, workOrderType = 1, searchKey = null, customerCode = null, customerName = null, feedbackRegion = null, electricianCode = null }) {
  try {
    const response = await axios.post('https://www.cqwuyang.cn/ElectricManageService/workOrder/findAllByCondition', {
      pageNum,
      pageSize,
      feedbackType,
      workOrderState,
      searchKey,
      customerCode,
      customerName: selectedCustomer.value,
      feedbackRegion: selectedRegion.value,
      electricianCode,
      workOrderType,
    })

    // 如果获取到数据，更新 dialogData
    if (response.data) {
      tableData.value = response.data.data.rows
      totalNum.value = response.data.data.total
      console.log('获取工单数据', response.data.data.rows)
    }
  }
  catch (error) {
    console.error('获取数据时出错:', error)
  }
}
// 获取电工信息
async function fetchWorkerData({ electricianState = 2, pageNum = '1', pageSize = '5' }) {
  try {
    const response = await axios.post('https://www.cqwuyang.cn/ElectricManageService/electrician/findAllByCondition', {
      pageNum,
      pageSize,
      electricianState,
    })

    // 如果获取到数据，更新 dialogData
    if (response.data) {
      console.log('获取电工信息', response.data.data.rows)
      electrician.value = response.data.data.rows
      totalWorker.value = response.data.data.total
    }
  }
  catch (error) {
    console.error('获取数据时出错:', error)
  }
}

onMounted(() => {
  fetchData({})
  fetchWorkerData({})
  // 在此处获取订单详情的逻辑
})
</script>

<template>
  <div class="dashboard">
    <div class="header">
      工单派遣
    </div>
    <!-- 筛选区域 -->
    <el-row :gutter="20" class="filter-row">
      <el-col :span="4">
        <el-input v-model="selectedRegion" style="width: 240px;" placeholder="请输入区域" />
      </el-col>
      <el-col :span="4">
        <el-input v-model="selectedCustomer" style="width: 240px;" placeholder="请输入单位名称" />
      </el-col>
      <el-col :span="4">
        <el-button type="primary" class="search-button" @click="fetchData({})">
          搜索
        </el-button>
      </el-col>
    </el-row>
    <!-- 数据表格 -->
    <el-table :data="tableData" border class="table" style="width: 100%; cursor: pointer;" @row-click="openOrderPage">
      <el-table-column prop="workOrderCode" label="工单号" align="center">
        <!-- <template #default="{ row }">
            <span v-if="row.workGlance === 0" class="red-dot"></span>
            <span>{{ row.workOrderCode }}</span>
          </template> -->
      </el-table-column>
      <el-table-column prop="customerName" label="业主单位" align="center" />
      <el-table-column prop="feedbackAddress" label="单位地址" align="center">
        <template #default="{ row }">
          <div class="multi-line-ellipsis">
            {{ row.feedbackAddress }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="workOrderContent" label="故障描述" align="center" />
      <el-table-column prop="workOrderCreateDate" label="工单生成时间" align="center" />
      <el-table-column prop="actions" label="操作" align="center">
        <template #default="{ row }">
          <el-button type="text" size="small" class="action-button"
            @click="(event) => { event.stopPropagation(); dispatchOrder(row.workOrderCode); }">
            定向派遣
          </el-button>
          <el-button type="text" size="small" class="action-button"
            @click="(event) => { event.stopPropagation(); releaseOrder(row.workOrderCode); }">
            发布抢单
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 派遣对话框 -->
    <el-dialog v-model="isDispatchDialogVisible" title="定向派遣工单" width="600px" @open="resetSelection">
      <!-- 搜索 -->
      <div style="display: flex; align-items: center; margin-bottom: 10px;">
        <span>请选择派遣电工</span>
        <el-input v-model="searchQuery" placeholder="请输入姓名" style=" width: 200px;margin-left: 10px;" />
        <el-button style="margin-left: 5px;" @click="searchWorker">
          搜索
        </el-button>
      </div>

      <!-- 表格 -->
      <el-table ref="tableRef" v-loading="loading" :data="electrician" border style="width: 100%;"
        :selection="selectedRows" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="electricianName" label="姓名" align="center" />
        <el-table-column prop="electricianPhone" label="电话" align="center" />
        <el-table-column prop="rating" label="评分" align="center" />
        <el-table-column prop="electricianRegion" label="所在区域" align="center" />
      </el-table>

      <!-- 分页 -->
      <el-pagination size="small" background layout="prev, pager, next" :total="totalWorker" class="mt-4"
        :current-page="currentWorkerPage" :default-page-size="5" @current-change="handleWorkerPageChange" />

      <!-- 响应时间 -->
      <div style="margin-top: 20px;">
        <span>请选择响应时间：</span>
        <el-select v-model="responseTime" placeholder="请选择响应时间" style="width: 150px;">
          <el-option v-for="hour in 10" :key="hour" :label="`${hour}小时`" :value="hour" />
        </el-select>
      </div>

      <!-- 按钮 -->
      <template #footer>
        <el-button @click="isDispatchDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" :disabled="!selectedWorker || !responseTime" @click="confirmDispatch">
          确定派遣
        </el-button>
      </template>
    </el-dialog>

    <!-- 发布对话框 -->
    <el-dialog v-model="isReleaseDialogVisible" title="发布详情" @open="resetSelection">
      <!-- 对话框内容 -->
      <p>当前工单号：{{ currentOrderId }}</p>
      <div style="margin-top: 20px;">
        <span>请选择响应时间：</span>
        <el-select v-model="responseTime" placeholder="请选择响应时间" style="width: 150px;">
          <el-option v-for="hour in 10" :key="hour" :label="`${hour}小时`" :value="hour" />
        </el-select>
      </div>
      <template #footer>
        <el-button @click="isReleaseDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" :disabled="!responseTime" @click="confirmRelease">
          确认发布
        </el-button>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <div class="pagination">
        <el-pagination size="normal" background layout="prev, pager, next" :total="totalNum" class="mt-4"
          :default-page-size="pageSize" @current-change="handlePageChange" />
      </div>
    </div>
  </div>
</template>

<style scoped>
.red-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  margin-left: 5px;
  background-color: red;
  border-radius: 50%;
}

.dashboard {
  padding: 20px;
  font-family: Arial, sans-serif;
}

.header {
  display: flex;
  justify-content: center;
  width: 30%;
  padding: 10px 20px;
  margin-bottom: 20px;

  /* 将分页按钮居中 */
  font-size: 24px;
  font-weight: bold;
  color: #333;
  text-align: center;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.filter-row {
  margin-bottom: 20px;
}

.search-button {
  color: white;
  background: linear-gradient(45deg, #3b82f6, #06b6d4);
  border: none;
  border-radius: 20px;
  box-shadow: 0 4px 8px rgb(0 0 0 / 10%);
}

.search-button:hover {
  background: linear-gradient(45deg, #06b6d4, #3b82f6);
}

.table {
  width: 1000px;
  margin-top: 20px;
  overflow: hidden;
  border-radius: 8px;
}

.table >>> .el-table__header-wrapper th {
  padding: 10px;
  font-size: 14px;
  font-weight: bold;
  color: #333;
  text-align: center;
  background-color: #f3f4f6;
  border-bottom: 2px solid #e5e7eb;
}

/* 地址部分，超过则显示省略号 */
.multi-line-ellipsis {
  display: -webkit-box;
  max-height: 3em;
  overflow: hidden;
  line-height: 1.5em;
  text-overflow: ellipsis;
  -webkit-line-clamp: 2;
  white-space: normal;
  -webkit-box-orient: vertical;
}

.action-button {
  padding: 4px 8px;
  font-weight: bold;
  color: #3b82f6;
  background-color: antiquewhite;
  border-radius: 5px;
  transition: all 0.2s;
}

.action-button:hover {
  background-color: #5382df;
  box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
}

.pagination {
  bottom: 20px;
  display: flex;

  /* 将分页按钮居中 */
  align-items: center;
  justify-content: center;
  padding: 10px 0;
  margin-top: 20px;
  background-color: #f9fafb;
  border-top: 1px solid #e5e7eb;
  border-radius: 0 0 8px 8px;
  box-shadow: 0 -2px 10px rgb(0 0 0 / 5%);
}

.pagination-wrapper {
  position: fixed;
  bottom: 20px;
  left: 280px;
  z-index: 10;
  align-items: center;
  width: 80%;
  padding: 10px 0;
}
</style>
